import json
from pyecharts.charts import Line
from pyecharts.options import *


def extract_json(jsonp_str):
    """提取JSONP中的JSON数据"""
    start = jsonp_str.find("(") + 1
    end = jsonp_str.rfind(")")
    return jsonp_str[start:end]


# 读取并解析数据
with open(r"D:\itheima\Python\可视化案例数据\折线图数据\美国.txt", "r", encoding="utf-8") as f:
    us_dict = json.loads(extract_json(f.read()))
with open(r"D:\itheima\Python\可视化案例数据\折线图数据\日本.txt", "r", encoding="utf-8") as f:
    jp_dict = json.loads(extract_json(f.read()))
with open(r"D:\itheima\Python\可视化案例数据\折线图数据\印度.txt", "r", encoding="utf-8") as f:
    in_dict = json.loads(extract_json(f.read()))


# 获取数据
def get_trend_data(data_dict, days=314):
    trend = data_dict['data'][0]['trend']
    dates = trend['updateDate'][:days]
    cases = trend['list'][0]['data'][:days]
    return dates, cases


us_x, us_y = get_trend_data(us_dict)
jp_x, jp_y = get_trend_data(jp_dict)
in_x, in_y = get_trend_data(in_dict)

# 创建折线图
line = Line(init_opts=InitOpts(width="1600px", height="800px"))

line.add_xaxis(us_x)  # 使用美国的日期作为x轴(假设三国日期相同)
line.add_yaxis("美国确诊", us_y,
               linestyle_opts=LineStyleOpts(width=3),
               label_opts=LabelOpts(is_show=False))
line.add_yaxis("日本确诊", jp_y,
               linestyle_opts=LineStyleOpts(width=3),
               label_opts=LabelOpts(is_show=False))
line.add_yaxis("印度确诊", in_y,
               linestyle_opts=LineStyleOpts(width=3),
               label_opts=LabelOpts(is_show=False))

line.set_global_opts(
    title_opts=TitleOpts(title="全球COVID-19确诊人数对比", pos_left="center"),
    tooltip_opts=TooltipOpts(trigger="axis"),
    legend_opts=LegendOpts(pos_top="8%"),
    toolbox_opts=ToolboxOpts(is_show=True),
    yaxis_opts=AxisOpts(
        name="确诊人数",
        type_="value",
        axislabel_opts=LabelOpts(formatter="{value} 人")
    ),
    xaxis_opts=AxisOpts(
        name="日期",
        axislabel_opts=LabelOpts(rotate=45)
    )
)

line.render("covid19_comparison.html")
